import pygame.sprite
import pygame
import Map
#import Common
from pygame.locals import *
import sys
#import math

class Entities():
   
   def __init__(self, screen, x, y): #initializes all the variables

      self.xmax = x #the max x boundary, after an entity passes this, its removed
      self.ymax = y #same as above but for y
      self.screen = screen
      self.ent = []
      self.keys = []
      self.allsprites = pygame.sprite.RenderPlain(self.ent)
      self.x, self.y = 0, 0
      #print "Entity Class Loaded"


   def loadent(self,entity): # loads an entity into the array and updates allsprites
      if type(entity) != pygame.sprite.Sprite:
         self.ent.append(entity)
         self.allsprites = pygame.sprite.RenderPlain(self.ent)
      else:
         print "wrong type"


   def removeent(self, index): # removes an entity from the array and updates allsprites
      self.ent.pop(index)
      self.allsprites = pygame.sprite.RenderPlain(self.ent)


   def checkent(self): # checks to make sure all the entities are in bounds
      i = 0
      while i < len(self.ent):
         cent = self.ent[i]
         if cent.x != None:
            if cent.x < 0 or cent.x > self.xmax:
               self.removeent(i)
         if cent.y != None:
            if cent.y < 0 or cent.y > self.ymax:
               self.removeent(i)
         i+=1


   def sendkey(self, str):

      i = 0

      while i < len(self.ent):
         try:
            self.ent[i].takekey(str)
            self.ent[i].update()
         except AttributeError:
            pass
         i += 1
   '''else:
      print "WRONG"'''


   #-----Timing-Function-----

   def Timing(self, framerate):
      self.time = self.clock.get_time()
      pygame.display.set_caption('M-7 Engine     press ESC to quit')
      if self.time < 1000/framerate:
         pygame.time.wait(1000/framerate - self.time)
         pygame.display.flip()
         if framerate < self.max:
            framerate += 1
      else:
         if framerate >= 1:
            framerate -= 1

      self.ticks = self.clock.tick()

   
   #-----Movement-----
   def Movein(self): # Linearly interpolates the movement of each Entity
      ent = self.ent
      i=0
      ax=0
      ay=0
      while i < len(ent):
         #this while loop gets the greatest value for a movement
         #and sets it to ax for x-movement and ay for y-movement
         try:
            if abs(ent[i].movex) > ax:
               ax = abs(ent[i].movex)
            if abs(ent[i].movey) > ay:
               ay = abs(ent[i].movey)
         except AttributeError:
            pass
         i+=1
      #then the greatest one is set to b
      if ax > ay:
         b = ax
      else:
         b = ay
      if b <= 0:
         pass

      #the seconds variable is used to make the entities move based on time
      seconds = self.ticks/1000.
      
      k = 0
      while k < b:
         j = 0
         while j < len(ent):
            try:
               
               ent[j].x += (seconds*ent[j].movex*ent[j].speed)/b
               ent[j].y += (seconds*ent[j].movey*ent[j].speed)/b

            except AttributeError:
               pass
            j+=1
         k+=1

   def run(self): # calls the checkent function, updates the sprites, and draws them to the screen
      self.clock = pygame.time.Clock()#initializes the clock
      self.ticks = self.clock.tick()#initializes the self.ticks variable
      
      sres = (800, 600)#screen resolution(work in progress)

      screen = pygame.display.set_mode(sres)
      pygame.display.set_caption('M-7 Engine     Press ESC to quit')
      pygame.mouse.set_visible(0)

      map = Map.Map(400, 300, self.ent)
      img = map.tile()

      framerate = 120 #this is the max number of frames rendered each second
      self.max = framerate
      running = True#this means it runs

      while running:
         
         #key input stuff
         keyinput = pygame.key.get_pressed()
         if keyinput[K_ESCAPE] or pygame.event.peek(QUIT):
            running = False
            sys.exit(0)
         if pygame.mouse.get_pressed()[0] == 1:
            pass
            #ent.loadent(play.shoot())
         if keyinput:
            self.keys = keyinput
         
         
         screen.fill((255,255,255))#fills the screen with white
         screen.blit(img, (0,0))
         self.sendkey(self.keys)
         self.checkent()
         self.Movein()
         self.allsprites.update()
         self.allsprites.draw(self.screen)
         self.Timing(framerate)
         